﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Configuration;
using System.IO;

using GG.Data;
using GG.Mail;

namespace GGNewLeadReportService
{
    public class NewLeadsStatus
    {
        public void NewLeadCount()
        {
            string _emailTitle = "";
            string _emailBody = "";
            string _toemail = "";
            string _ccemail = "";
            string _bccemail = "";
            string _contactusemail = "";

            try
            {
                MyData mydata = new MyData();
                if (mydata.GetEventCount() == 0)
                {
                    // *** Not Holiday ***
                    DateTime _dtDate = GG.Global.General.GetUTCDateTime();

                    _emailTitle = "GG New Leads @ " + _dtDate.ToString("dd/MM/yyyy"); // + "  (" + _dtDate.ToString(" hh tt") + ")"
                    
                    _toemail = System.Configuration.ConfigurationSettings.AppSettings["toemail"].ToString();
                    _ccemail = System.Configuration.ConfigurationSettings.AppSettings["ccemail"].ToString();
                    _bccemail = System.Configuration.ConfigurationSettings.AppSettings["bccemail"].ToString();
                    _contactusemail = System.Configuration.ConfigurationSettings.AppSettings["contactusemail"].ToString();

                    Int32 NewLeadPreDay = 0; Int32 NewLeadToday = 0;
                    Int32 NewLeadTotal = 0; Int32 NewLeadAssignToday = 0;
                    Int32 OldLeadAvailable = 0; Int32 OldLeadAssignToday = 0; 
                    Int32 BalanceNewLeads = 0; Int32 BalanceOldLeads = 0;
                    Int32 NewFacebookToday = 0;

                    DataSet _dsAgentLeads = new DataSet();
                    _dsAgentLeads = mydata.GetNewLeads();

                    #region New Leads
                    if (_dsAgentLeads != null && _dsAgentLeads.Tables.Count > 0 && _dsAgentLeads.Tables[0].Rows.Count > 0)
                    {
                        DataRow _drAgentLeads = _dsAgentLeads.Tables[0].Rows[0];
                        if (_drAgentLeads["NewLeadPreDay"] != DBNull.Value && _drAgentLeads["NewLeadPreDay"].ToString() != string.Empty)
                        {
                            NewLeadPreDay = Convert.ToInt32(_drAgentLeads["NewLeadPreDay"].ToString());
                        }
                        if (_drAgentLeads["NewLeadToday"] != DBNull.Value && _drAgentLeads["NewLeadToday"].ToString() != string.Empty)
                        {
                            NewLeadToday = Convert.ToInt32(_drAgentLeads["NewLeadToday"].ToString());
                        }
                        if (_drAgentLeads["OldLeadAvailable"] != DBNull.Value && _drAgentLeads["OldLeadAvailable"].ToString() != string.Empty)
                        {
                            OldLeadAvailable = Convert.ToInt32(_drAgentLeads["OldLeadAvailable"].ToString());
                        }
                        if (_drAgentLeads["NewLeadAssignToday"] != DBNull.Value && _drAgentLeads["NewLeadAssignToday"].ToString() != string.Empty)
                        {
                            NewLeadAssignToday = Convert.ToInt32(_drAgentLeads["NewLeadAssignToday"].ToString());
                        }
                        if (_drAgentLeads["NewFacebookToday"] != DBNull.Value && _drAgentLeads["NewFacebookToday"].ToString() != string.Empty)
                        {
                            NewFacebookToday = Convert.ToInt32(_drAgentLeads["NewFacebookToday"].ToString());
                        }
                        if (_drAgentLeads["OldLeadAssignToday"] != DBNull.Value && _drAgentLeads["OldLeadAssignToday"].ToString() != string.Empty)
                        {
                            OldLeadAssignToday = Convert.ToInt32(_drAgentLeads["OldLeadAssignToday"].ToString());
                        }
                    }

                    NewLeadTotal = NewLeadPreDay + NewLeadToday;
                    BalanceNewLeads = NewLeadTotal - NewLeadAssignToday - NewFacebookToday;
                    BalanceOldLeads = OldLeadAvailable - OldLeadAssignToday;

                    #endregion

                    #region LEADS LIST
                    _emailBody += "<html>";
                    _emailBody += "<head>";
                    _emailBody += "<title></title>";
                    _emailBody += "</head>";
                    _emailBody += "<body class='email_body'>";

                    _emailBody += "<style type='text/css'>";
                    _emailBody += ".email_body {background: white;margin: 0;padding: 0;color: #4c4c4c;font-family: Arial, Helvetica, sans-serif;font-size: 0.85em;}";
                    _emailBody += "a {text-decoration:underline;color:#2c95cc;} ";
                    _emailBody += "#email_container {margin:0 auto;padding:20px;width:600px; height:auto;} ";
                    _emailBody += "#email_body {width:100%; text-align: left !important;} ";
                    _emailBody += ".email_pad10px {padding:10px;} ";
                    _emailBody += ".email_results td {width:33%;} ";
                    _emailBody += "</style>";

                    _emailBody += "<table width='75%' border='0' cellspacing='2' cellpadding='0' class='email_body'>";
                    _emailBody += "<tr><td style='color:#DF7401; font-size:large;'><b>GG New Lead Status at " + _dtDate.ToString("dd/MM/yyyy") + "</b></td></tr>";

                    _emailBody += "<tr><td>";
                    _emailBody += "<table width='100%' border='1' cellspacing='2' cellpadding='0' class='email_body'>";
                    _emailBody += "<tr>";
                    _emailBody += "<td style='width: 300px; height:30px; background: #045FB4; color:#ffffff;' align='center'></td>";
                    _emailBody += "<td style='width: 80px; height:30px; background: #045FB4; color:#ffffff;' align='center'><b>New Leads</b></td>";
                    _emailBody += "</tr>";
                    _emailBody += "<tr>";
                    _emailBody += "<td style='height:30px; background: #ffdb0f;' align='left'>New leads brought forward from previous day</br>(created but not assigned)</td>";
                    _emailBody += "<td style='height:30px; background: #ffdb0f;' align='right'>" + NewLeadPreDay.ToString() + "</td>";
                    _emailBody += "</tr>";
                    _emailBody += "<tr>";
                    _emailBody += "<td style='height:30px; background: #ffdb0f;' align='left'>New leads created today</td>";
                    _emailBody += "<td style='height:30px; background: #ffdb0f;' align='right'>" + NewLeadToday.ToString() + "</td>";
                    _emailBody += "</tr>";
                    _emailBody += "<tr>";
                    _emailBody += "<td style='height:30px; background: #ffdb0f;' align='right'>Total new leads</td>";
                    _emailBody += "<td style='height:30px; background: #ffdb0f;' align='right'>" + NewLeadTotal.ToString() + "</td>";
                    _emailBody += "</tr>";
                    _emailBody += "<tr>";
                    _emailBody += "<td style='height:30px; background: #ffdb0f;' align='left'>New leads assigned (GG Login)</td>";
                    _emailBody += "<td style='height:30px; background: #ffdb0f;' align='right'>" + NewLeadAssignToday.ToString() + "</td>";
                    _emailBody += "</tr>";
                    _emailBody += "<tr>";
                    _emailBody += "<td style='height:30px; background: #ffdb0f;' align='left'>New leads assigned (Facebook Login)</td>";
                    _emailBody += "<td style='height:30px; background: #ffdb0f;' align='right'>" + NewFacebookToday.ToString() + "</td>";
                    _emailBody += "</tr>";
                    _emailBody += "<tr>";
                    _emailBody += "<td style='height:30px; background: #a8a8a8;' align='right'>Balance new leads</td>";
                    _emailBody += "<td style='height:30px; background: #a8a8a8;' align='right'>" + BalanceNewLeads.ToString() + "</td>";
                    _emailBody += "</tr>";
                    _emailBody += "</table>";
                    _emailBody += "</td></tr>";
                    _emailBody += "<tr><td>";
                    _emailBody += "<table width='100%' border='1' cellspacing='2' cellpadding='0' class='email_body'>";
                    _emailBody += "<tr>";
                    _emailBody += "<td style='width: 300px; height:30px; background: #045FB4; color:#ffffff;' align='center'></td>";
                    _emailBody += "<td style='width: 80px; height:30px; background: #045FB4; color:#ffffff;' align='center'><b>Old Leads</b></td>";
                    _emailBody += "</tr>";
                    _emailBody += "<tr>";
                    _emailBody += "<td style='height:30px; background: #ffdb0f;' align='left'>Old leads available</td>";
                    _emailBody += "<td style='height:30px; background: #ffdb0f;' align='right'>" + OldLeadAvailable.ToString() + "</td>";
                    _emailBody += "</tr>";
                    _emailBody += "<tr>";
                    _emailBody += "<td style='height:30px; background: #ffdb0f;' align='left'>Old leads assigned</td>";
                    _emailBody += "<td style='height:30px; background: #ffdb0f;' align='right'>" + OldLeadAssignToday.ToString() + "</td>";
                    _emailBody += "</tr>";
                    _emailBody += "<tr>";
                    _emailBody += "<td style='height:30px; background: #a8a8a8;' align='right'>Balance old leads</td>";
                    _emailBody += "<td style='height:30px; background: #a8a8a8;' align='right'>" + BalanceOldLeads.ToString() + "</td>";
                    _emailBody += "</tr>";
                    _emailBody += "</table>";
                    _emailBody += "</td></tr>";
                    _emailBody += "</table>";
                    _emailBody += "</body>";
                    _emailBody += "</html>";

                    string IsMailSend = ConfigurationManager.AppSettings["IsMailSend"].ToString();
                    if (IsMailSend.ToString() != string.Empty && IsMailSend == "1")
                    {
                        #region Email - Agent Call List
                        int countError = 0;
                        bool _emailSend = false;
                        while (!_emailSend)
                        {
                            if (MyMailManager.SendEmail(_emailTitle, _emailBody, _toemail, _ccemail, _bccemail))
                            {
                                _emailSend = true;
                                CreateExceptionLog(new Exception("GG New Leads Sent successfully [" +
                                    GG.Global.General.GetUTCDateTime().ToString() + "]."));
                            }
                            else
                            {
                                CreateExceptionLog(new Exception("GG New Leads can't be Sent [" +
                                    GG.Global.General.GetUTCDateTime().ToString() + "]."));
                                countError++;
                                if (countError >= 2)
                                    return;
                            }
                        }
                        #endregion
                    }
                    #endregion
                }
                else
                {
                    CreateExceptionLog(new Exception("Public Holiday [" + GG.Global.General.GetUTCDateTime().ToString() + "]."));
                }
            }
            catch (Exception Ex)
            {
            }
        }

        #region Error File

        private void CreateExceptionLog(Exception Ex)
        {
            String[] _fileContent = new String[5];
            _fileContent[0] = "Source : " + Ex.Source;
            _fileContent[1] = "Date Time : " + DateTime.Now.ToString();
            _fileContent[2] = "Message : " + Ex.Message;

            WriteExceptionLog("Ex_", _fileContent);
        }

        private void WriteExceptionLog(string strPrefixFileName, string[] strException)
        {
            try
            {
                string _filePath = AppDomain.CurrentDomain.BaseDirectory + "Error\\";
                if (CheckDirectory(_filePath))
                {
                    string _curMonth = DateTime.Now.Year.ToString("0000") + DateTime.Now.Month.ToString("00");

                    if (!CheckDirectory(_filePath + _curMonth))
                    {
                        if (CreateDirectory(_filePath, _curMonth))
                        {
                            _filePath += _curMonth + "\\";
                        }
                    }
                    else
                    {
                        _filePath += _curMonth + "\\";
                    }

                    string _fileName = strPrefixFileName + _curMonth + DateTime.Now.Day.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("00") + ".txt";

                    WriteNewFile(_filePath, _fileName, strException);
                }
            }
            catch (Exception Ex)
            {
                Ex = null;
            }
        }

        public bool CheckDirectory(string filePath)
        {
            bool _retvalue = false;
            DirectoryInfo _dirinfo = null;
            try
            {
                _dirinfo = new DirectoryInfo(filePath);
                _retvalue = _dirinfo.Exists;
            }
            catch (Exception Ex)
            {
                Ex = null;
                _retvalue = false;
            }
            finally
            {
                _dirinfo = null;
            }
            return _retvalue;
        }

        public bool CreateDirectory(string filePath, string DirName)
        {
            bool _retValue = false;
            DirectoryInfo _dirinfo = null;
            DirectoryInfo _newDir = null;
            try
            {
                _dirinfo = new DirectoryInfo(filePath + DirName);
                if (_dirinfo.Exists)
                {
                    _retValue = false;
                }
                else
                {
                    _dirinfo = new DirectoryInfo(filePath);
                    if (_dirinfo.Exists)
                    {
                        _newDir = _dirinfo.CreateSubdirectory(DirName);
                        _retValue = _newDir.Exists;
                    }
                    else
                    {
                        _retValue = false;
                    }
                }
            }
            catch (Exception Ex)
            {
                Ex = null;
                _retValue = false;
            }
            finally
            {
                _dirinfo = null;
                _newDir = null;
            }

            return _retValue;
        }

        public bool WriteNewFile(string filePath, string fileName, string[] fileContent)
        {
            StreamWriter _writer = null;
            try
            {
                _writer = new StreamWriter(filePath + fileName);
                for (int l = 0; l < fileContent.Length; l++)
                {
                    _writer.WriteLine(fileContent[l]);
                }
                if (_writer != null)
                {
                    _writer.Flush();
                    _writer.Close();
                }
            }
            catch (Exception Ex)
            {
                Ex = null;
            }
            finally
            {
                if (_writer != null)
                {
                    //_writer.Flush();
                    //_writer.Dispose();
                    _writer = null;
                }
            }
            return true;
        }

        #endregion
    }
}
